This page has been superceded by a wiki version of this example: CurrencyExample



/*
    Title:   Currency with Operator Overloading
    File:    currency.d
    Author:  J C Calvarese, http://jcc_7.tripod.com/d/
    Date:    2004/01/03
    Licence: Public domain


    TEST version: outputs more information to the console during run.
*/


import std.string;
import std.math;



char[] leadingZeros(byte num, byte digits)
/* by J C Calvarese, also in locales2.d and with.d */
{ 
    char[] buffer;
    byte diff;
    
    buffer = toString(num);
    if (buffer.length < digits) 
    {
        diff = digits - buffer.length;
        for(int i=0; i < diff; i++)
          buffer = "0" ~ buffer;
    } 
    return buffer;
}



char[] toStringFromDouble(double d)
{
    return toStringFromDouble(d, 2); /* defaults to 2 decimal places */ 
}

char[] toStringFromDouble(double d, int decPlaces)
{
    return toStringFromDouble(d, decPlaces, "."); /* separator defaults to period */ 
}

char[] toStringFromDouble(double i, int decPlaces, char[] sep)
{  
    int whole;
    int dec;
    double decPart;
    
    whole = cast(int) i;
    version(TEST) printf("whole: %d\n", whole);

    decPart = (i - whole) * pow(cast(real) 10, cast(uint) decPlaces);
    version(TEST) printf("decPart: %lf\n", decPart);
    
    dec = cast(int) (decPart);
    version(TEST) printf("dec: %d\n", dec);
    return toString(i) ~ sep ~ leadingZeros(dec, decPlaces);
}



class Currency
{   
    /* Read property ("get-ter") */
    double value() {return intValue;}
    
    /* Write property ("set-ter") */
    double value(double v) {return intValue = v;}

    
    this(double v)
    {
        version(TEST) printf("An instance of the Currency object is created.\n\n");
        intValue = v;
        intSeparator = ".";
        intDecPlaces = 2;
    }
    
    this()
    {
        this(0);
    }
    
    char[] toString() { return toStringFromDouble(intValue, intDecPlaces, intSeparator);}



    /* operator overloading */

    Currency opAdd(Currency m, Currency n)
    {  
        Currency t;
        t.value = m.value + n.value;
        return t;
    }

    Currency opAddAssign(Currency m)
    {  
        intValue += m.value;
        return this;
    }


    private 
    {
        double intValue;
        double intDecPlaces;
        char[] intSeparator; /* decimal, period (U.S.), comma (Some non-U.S. locations) */
    }
}



void main()
{ 
    Currency c = new Currency();  
    printf("\n\t\t\t\t\t\t%.*s\n", c.toString);

    printf("Change the value:\t\t\t\t");
    c.value = 100.75;
    printf("%.*s\n", c.toString);

    Currency c2 = new Currency(26.12);
    printf("\t\t\t\t\t\t%.*s\n", c2.toString);

    printf("Change the value:\t\t\t\t");
    c2.value = 6.25;
    printf("%.*s\n", c2.toString);

    printf("Change the value (operator overloading):\t");
    c2 += c; /* requires operator overloading */
    printf("%.*s\n\n", c2.toString);
}